const path = require('path')
const fs = require('fs');

const walk = require('walk');
const upyun = require('upyun');

const upyunConfig = {
  serviceName: 'file-open-chihe-so',
  user: 'fileopen',
  password: 'fileopen'
};

const distRoot = path.resolve(__dirname, 'dist');
const upyunRoot = '/open-static';

function eachDist() {
  return new Promise((res, rej) => {
    let walker = walk.walk(distRoot);
    let files = [];

    walker.on('file', (root, fileStats, next) => {
      let { name } = fileStats;

      if (name.substr(0, 1) !== '.') {
        files.push(`${root}/${name}`)
      }

      next()
    })

    walker.on('end', () => res(files))
    walker.on('errors', rej)
  })
}

(async () => {
  try {
    let files = await eachDist();
    let slice = distRoot.length;

    let { serviceName, user, password } = upyunConfig;
    let Service = new upyun.Service(serviceName, user, password);
    let Client = new upyun.Client(Service);

    files.push(files.shift())

    for (let file of files) {
      let upyunPath = path.join(upyunRoot, file.slice(slice));

      if (await Client.putFile(upyunPath, fs.readFileSync(file))) {
        console.log(`${file} -> ${upyunPath}`)
      } else {
        throw new Error(`Upload ${file} fail`)
      }
    }

    process.exit()
  } catch (e) {
    console.error(e.message)
    process.exit(-100)
  }
})()
